var copyText = function () {
        var textArea = document.getElementsByClassName('toText')[0]
        // 选中文本
        textArea.select()
        // 复制
        document.execCommand('copy');
        alert("已复制到剪切板")
}

var fromTextEle = $(".fromText"),
        toTextELe = $(".toText"),
        switchBtnEle = $(".switchBtn"),
        appid = "20210323000739360", // 设置默认appid
        key = "82GT5f3GpFEjNsNBPF1c"; // 设置默认key

// 关于appid和key信息，强烈建议同学们自行免费申请，避免卡顿
// 申请地址: https://api.fanyi.baidu.com/api/trans/product/apichoose

/*
初级	中->英->德->中
中级	中->英->德->日->葡萄牙->中
高级	中->英->德->日->葡萄牙->意大利->波兰->保加利亚->爱沙尼亚->中
*/
var transList = {
        simple: ["zh en", "en de", "de zh"],
        middle: ["zh en", "en de", "de jp", "jp pt", "pt zh"],
        high: [
                "zh en",
                "en de",
                "de jp",
                "jp pt",
                "pt it",
                "it pl",
                "pl bul",
                "bul est",
                "est zh",
        ],
};

var mode = "simple";

// 生成API参数
function genParams(q, from, to) {
        var url = "https://fanyi-api.baidu.com/api/trans/vip/translate";
        var data = {
                q: q,
                from: from,
                to: to,
                appid: appid,
                salt: "",
                sign: "",
        };

        data.salt = Math.floor(Math.random() * 10000000000);
        data.sign = md5(appid + q + data.salt + key);

        return { url, data };
}

// 翻译
function translate(q, from, to) {
        var params = genParams(q, from, to);

        return new Promise((resolve, reject) => {
                $.ajax({
                        type: "POST",
                        url: params.url,
                        data: params.data,
                        dataType: "jsonp",
                        headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                        },
                        success: (res) => {
                                log("from: " + from, "; ", "to:" + to);
                                resolve(res);
                        },
                        error: () => {
                                reject();
                        },
                });
        });
}

// 翻译队列
function queen(str) {
        var dst = str;
        (async () => {
                for (let i = 0; i < transList[mode].length; i++) {
                        var lang = transList[mode][i].split(" ");
                        res = await translate(dst, lang[0], lang[1]);
                        dst = res.trans_result[0].dst;
                        log("result: ", dst);
                }
                toTextELe.text(dst);
        })();
}

// 开始翻译
function starSwitch() {
        appid = $(".appid").val();
        key = $(".key").val();
        if (fromTextEle.val() === "" || appid === "" || key === "") {
                log("请将appid key和要翻译的文本补充完整");
                return false;
        }

        mode = $(".level option:selected").val();

        setCacheData();

        queen(fromTextEle.val());
}

// 日志
function log(...params) {
        var insertStr = params.join("");
        logEle = $(".log");
        logEle.text(insertStr + "\n" + logEle.text());
}

// 缓存appid和key
function setCacheData() {
        localStorage.setItem("appid", $(".appid").val());
        localStorage.setItem("key", $(".key").val());
}

// 读取缓存中的appid和key
function getCacheData() {
        var appid = localStorage.getItem("appid");
        var key = localStorage.getItem("key");
        if (appid + key + $(".appid").val() + $(".key").val() !== "") {
                $(".appid").val(appid);
                $(".key").val(key);
        }
}

function init() {
        getCacheData();
        $(".switchBtn").click(starSwitch);
}

init();